package com.example.service;

import com.example.pojo.dto.UserDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.pojo.User;
import com.example.repository.IUserRepository;

// @Service 和 @Component的区别 都可以实现自行注入 spring的bean
@Service
public class UserService implements IUserService {

    @Autowired
    IUserRepository userRepository;

    @Override
    public User add(UserDto user) {

        // 调用数据访问类
        User userCopy = new User();

        // 调用BeanUtils.copyProperties方法,将userDto中的属性值复制到userCopy中
        // 第一个参数: 源对象
        // 第二个参数: 目标对象
        BeanUtils.copyProperties(user, userCopy);
        return userRepository.save(userCopy);
    }

    @Override
    public User getUser(Integer userId) {
        return userRepository.findById(userId).orElseThrow(() -> {
            throw new IllegalArgumentException("用户不存在,参数异常");
        });
    }

    @Override
    public User edit(UserDto user) {
        User existUser = userRepository.findById(user.getId()).orElseThrow(() -> {
            throw new IllegalArgumentException("用户id不存在");
        });
        BeanUtils.copyProperties(user, existUser);
        return userRepository.save(existUser);
    }

    @Override
    public void delete(Integer id) {
        userRepository.findById(id).orElseThrow(() -> {
            throw new IllegalArgumentException("用户id不存在");
        });
        userRepository.deleteById(id);
    }
}
